package controller;

import java.io.File;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.pagehelper.PageInfo;

import domain.Message;
import domain.Music;
import exception.FormatException;
import service.IMusicService;
import utils.FileUtil;

/**
 * @author LGW
 *	这里把前台和后台的Controller写在一起
 */
@Controller
public class MusicController {
	@Autowired
	private IMusicService service;

	//前台的跳转到music  同事取出数据库中的音乐信息
	@RequestMapping("/music")
	public String goMusic(HttpServletRequest req, Integer page) {
		Integer size = 9;//默认为一页9条数据
		if (page == null) {
			page = 1; //若请求中没有分页的信息 就从第一页开始
		}
		List<Music> all = service.listAll(page, size);
		PageInfo<Message> pageInfo = new PageInfo(all);
		//将pageInfo放到请求中做分页
		req.setAttribute("pageInfo", pageInfo);
		req.setAttribute("music", all);
		return "front/music";
	}

	//前台的下载功能
	@RequestMapping("/download")
	public void downMusic(HttpServletRequest req, HttpServletResponse resp, String path, String musicName)
			throws Exception {
		//获取被下载的资源文件名
		String fileName = path.substring(17);
		//得到后缀名 主要是为了下载时的名字的后缀
		String end = fileName.substring(36);
		//解码
		fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
		//从服务器中找到下载资源的绝对路径
		String realPath = req.getSession().getServletContext().getRealPath("/music") + "\\"+fileName;
		//磁盘中的文件-->程序-->浏览器
		//这是告诉浏览器这是一个要保存到本地的下载的文件
		resp.setContentType("application/x-msdownload");
		//设置下载文件名
		if (req.getHeader("User-Agent").contains("Trident")) { //貌似我的Edge里面没有MSIE
			fileName = URLEncoder.encode(musicName + end, "utf-8"); //针对IE 对Google也有效但是对Firefox没用
		} else {
			fileName = new String((musicName + end).getBytes("utf-8"), "ISO-8859-1"); //与上面相反
		}
		resp.addHeader("content-disposition", "attachment;filename=" + fileName);
		Files.copy(Paths.get(realPath), resp.getOutputStream());
	}

	//后台的跳转
	@RequestMapping("/sharemusic")
	public String goAdminMusic(HttpServletRequest req,Integer page) {
		Integer size = 7;//默认为一页9条数据
		if (page == null) {
			page = 1; //若请求中没有分页的信息 就从第一页开始
		}
		List<Music> all = service.listAll(page, size);
		PageInfo<Message> pageInfo = new PageInfo(all);
		//将pageInfo放到请求中做分页
		req.setAttribute("pageInfo", pageInfo);
		//拦截器写好了，那个path里不需要加上下文路径。。。
		req.setAttribute("music", all);
		//在这里生成token 
		String token = UUID.randomUUID().toString();
		req.setAttribute("tokenInForm", token);
		req.getSession().setAttribute("tokenInSession", token);
		return "admin/music";
	}

	@RequestMapping("/addMusic")
	public void addMusic(HttpServletRequest req, HttpServletResponse resp/*, String name, String desc*/)
			throws Exception {
		Music music = new Music();
		
		//music.setName(req.getParameter("name")); 仍然得不到值  
		//music.setDescript(req.getParameter("desc"));   突然想起来这里的表单格式似乎对这里是有影响的 以往都是普通的 这一个是二进制的
		//所以就应该在 解析请求的里面去 设置值或者让它返回出来 这里我就写死了。
		//music.setName(name);  存疑这样得不到值
		//music.setDescript(desc);
		//上面传递过来的req如果在springmvc中配置了 那就是是已经由mvc处理过的请求 这里 我采用自己处理的方式

		//这里可以把session中的token拿到 当参数 传递给 FileUtil里面 判断表单里得 和session里的是否一样
		//这里处理下这个异常
		try {
			music = FileUtil.upload(req, (String) req.getSession().getAttribute("tokenInSession"));
		}catch(FormatException e) {
			req.setAttribute("isSuccess", e.getMessage());
			req.getRequestDispatcher("/sharemusic").forward(req, resp);
			//结束方法
			return;
		}
		if (music == null) {
			//若重复提交就提前return
			resp.sendRedirect("/sharemusic");
			//一开始忘记return  添加音乐表单会重复提交
			return;
		}
		req.getSession().removeAttribute("tokenInSession");	//程序走到这里说明成功提交，销毁口令
		Integer state = service.addMusic(music);
		if (state > 0) {
			req.setAttribute("isSuccess", "SUCCESS");
		} else {
			req.setAttribute("isSuccess", "FAIL");
		}
		req.getRequestDispatcher("/sharemusic").forward(req, resp);
	}

	@RequestMapping("/mucDelete")
	public void deleteMusic(HttpServletRequest req, HttpServletResponse resp, Long id,String name) throws Exception {
		Integer state = service.deleteMusic(id);
		//这里留着实现真正的删除
		String fileName = name.substring(17); //很low的方法，应该用正则表达式
		//解码
		fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
		//从服务器中找到下载资`源的绝对路径
		//写死了  这里终于把Tomcat的路径换了不用哪个克隆的了
		String realPath = req.getSession().getServletContext().getRealPath("/music")+"\\"+ fileName;
		//System.out.println(realPath);
		File musicFile=new File(realPath);
		boolean delete=false;
		if(musicFile.exists()&&musicFile.isFile()) {
			 delete = musicFile.delete();
		}
		if (state > 0&&delete) {
			req.setAttribute("isSuccess", "SUCCESS");
		} else {
			req.setAttribute("isSuccess", "FAIL");
		}
		req.getRequestDispatcher("/sharemusic").forward(req, resp);
	}
}
